<script src="/theme/Default/js/jquery-2.1.1.min.js"></script>

<img id="loader" title="Loading...." alt="Loading...." src="/theme/Default/img/loader.gif" style="display: none;">
<form id="form" enctype="multipart/form-data" method="post" action="/postingFree/uploadImage">
<input id="uploadImage" type="file" name="image" accept="image/*">
<a id="button" href="#">upload</a>
</form>
<div id="preview" style="display:none"></div>
<script>
$(document).ready(function() {
	var f = $('form');
	var l = $('#loader'); // loder.gif image
	var b = $('#button'); // upload button
	var p = $('#preview'); // preview area
	
	b.click(function(e){
		val = $('#uploadImage').val();
		if(val!=""){
			prepareUpload(e);
			e.preventDefault();
		}
	});
	
	function prepareUpload(e){
        files = $('#uploadImage').prop('files');
        var fd = new FormData();
        fd.append("image", files[0]);
        $.ajax({
            url : "/postingFree/uploadImage",
            type : "POST",
            data : fd,
            contentType: false,
            processData:false,
            beforeSend: function(){
				l.show();
				b.attr('disabled', 'disabled');
				p.fadeOut();
			},
			success: function(data){
				l.hide();
				b.removeAttr('disabled');
				p.append(data).fadeIn();
				$('#uploadImage').val("");
			},
			error: function(error){
				b.removeAttr('disabled');
				p.html(error).fadeIn();
			}
        });
    }
    $(document).on('click', '.removeImage', function(e){
    	src = $(this).closest('div').find("img").attr("src");
    	console.log(src);
    	deleteImage(src, $(this));
    	
    });
    function deleteImage(srcFile, $btn){
    	$.ajax({
            url : "/postingFree/deleteImage",
            type : "POST",
            dataType : "json",
            data : {
                "src" : srcFile
            },
            beforeSend: function(){
				
			},
			success: function(data){
				$btn.closest("div").remove();
			},
			error: function(error){
				alert("không xóa được");
			}
        });
    }
});
</script>